package com.hjb.service.impl.product;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.hjb.service.config.constant.Constants;
import com.hjb.service.domain.common.ActivityRule;
import com.hjb.service.domain.common.ActivityRuleExample;
import com.hjb.service.domain.product.Product;
import com.hjb.service.domain.product.SiteUserBuy;
import com.hjb.service.domain.product.SiteUserBuyExample;
import com.hjb.service.domain.recharge.SiteUserRecharge;
import com.hjb.service.domain.siteuser.SiteUserAccountLog;
import com.hjb.service.domain.siteuser.SiteUserAddRate;
import com.hjb.service.domain.siteuser.SiteUserCurrent;
import com.hjb.service.domain.siteuser.SiteUserFixed;
import com.hjb.service.domain.siteuseraccount.SiteUserAccount;
import com.hjb.service.domain.siteusercoupon.SiteUserCoupon;
import com.hjb.service.domain.siteuserenvelop.SiteUserEnvelop;
import com.hjb.service.mapper.ActivityRuleMapper;
import com.hjb.service.mapper.ProductMapper;
import com.hjb.service.mapper.SiteUserAccountLogMapper;
import com.hjb.service.mapper.SiteUserAccountMapper;
import com.hjb.service.mapper.SiteUserAddRateMapper;
import com.hjb.service.mapper.SiteUserBuyMapper;
import com.hjb.service.mapper.SiteUserCouponMapper;
import com.hjb.service.mapper.SiteUserCurrentMapper;
import com.hjb.service.mapper.SiteUserFixedMapper;
import com.hjb.service.product.SiteUserBuyService;
import com.hjb.service.user.SiteSysAccountService;
import com.hjb.service.user.SiteUserAccountService;
import com.hjb.service.user.SiteUserCouponService;
import com.hjb.service.user.SiteUserEnvelopService;
import com.hjb.service.utils.HJBUT;

/**
 * 产品接口业务实现类
 * @author zhangxl
 * @date 2017-07-28
 * @version 1.0
 */
@Service
public class SiteUserBuyServiceImpl implements SiteUserBuyService {

	private Logger log = LoggerFactory.getLogger(getClass());
	
	@Autowired
	private SiteUserBuyMapper siteUserBuyMapper;
	@Autowired
	private SiteUserCurrentMapper siteUserCurrentMapper;
	@Autowired
	private SiteUserCouponMapper siteUserCouponMapper;
	@Autowired
	private SiteUserAddRateMapper siteUserAddRateMapper;
	@Autowired
	private SiteUserFixedMapper siteUserFixedMapper;
	@Autowired
	private SiteUserAccountService siteUserAccountService;
	@Autowired
	private ProductMapper productMapper;
	@Autowired
	private SiteUserAccountMapper siteUserAccountMapper;
	@Autowired
	private SiteUserAccountLogMapper siteUserAccountLogMapper;
	@Autowired
	private ActivityRuleMapper activityRuleMapper;
	@Autowired
	private SiteUserCouponService siteUserCouponService;
	@Autowired
	private SiteUserEnvelopService siteUserEnvelopService;
	@Autowired
	private SiteSysAccountService siteSysAccountService;
	
	@Override
	public int insertSiteUserBuy(SiteUserBuy siteUserBuy) {
		return siteUserBuyMapper.insertSelective(siteUserBuy);
	}

	@Override
	public List<SiteUserBuy> selectByExample(SiteUserBuyExample example) {
		return siteUserBuyMapper.selectByExample(example);
	}

	@Override
	public BigDecimal queryBidAmountTotal(Map<String,Object> params) {
		return siteUserBuyMapper.queryBidAmountTotal(params);
	}

	@Override
	public BigDecimal queryBidAmountByProductId(String productId) {
		return siteUserBuyMapper.queryBidAmountByProductId(productId);
	}

	@Override
	public List<Map<String, Object>> queryInvestDynaList(Map<String, Object> params) {
		List<Map<String, Object>> dynaList = new ArrayList<Map<String,Object>>();
		List<Map<String, Object>> resList =siteUserBuyMapper.queryInvestDynaList(params);
		for(Map<String, Object> resMap: resList){
			if(resMap.get("mobile_phone") !=null){
				String mobile = String.valueOf(resMap.get("mobile_phone"));
				mobile = mobile.substring(0,3)+"****"+mobile.substring(mobile.length()-4,mobile.length());
				Map<String, Object> dysnMap = new HashMap<String, Object>();
				BigDecimal amount = new BigDecimal(String.valueOf(resMap.get("amount")));
				dysnMap.put("infoStr", "用户"+mobile+" 投资"+amount.setScale(2,BigDecimal.ROUND_DOWN)+"元");
				dynaList.add(dysnMap);
			}
		}
		
		return dynaList;
	}

	@Override
	@Transactional
	public void rechargeNotify(SiteUserRecharge userRecharge) {
		log.info("充值购买成功回调开始................................."+HJBUT.currentTime());
		log.info("充值购买成功回调：order_id:"+userRecharge.getOrderId());
		log.info("充值结果状态："+userRecharge.getStatus());
		log.info("充值结果信息："+userRecharge.getRetMsgConf());
		
		SiteUserBuyExample userBuyExample = new SiteUserBuyExample();
		userBuyExample.createCriteria().andOrderNoEqualTo(userRecharge.getOrderId()).andUserIdEqualTo(userRecharge.getUserId());
		List<SiteUserBuy> siteUserBuyList = siteUserBuyMapper.selectByExample(userBuyExample);
		log.info("siteUserBuyList 条数"+siteUserBuyList.size());
		if(siteUserBuyList == null){
			log.info("充值结果 充值失败！购买记录不存在"+userRecharge.getOrderId());
			return;
		}
		
		SiteUserBuy queryUserBuy = siteUserBuyList.get(0);
		log.info("SiteUserBuy====="+queryUserBuy.getOrderNo()+"状态："+queryUserBuy.getStatus());
		if(queryUserBuy.getStatus() != Constants.COMMON_STATUS_0){
			log.info("充值结果 充值失败！该记录已处理或重复处理"+userRecharge.getOrderId());
			return;
		}
		
		SiteUserBuy userBuy = new SiteUserBuy();
		userBuy.setId(queryUserBuy.getId());
		userBuy.setReplyTime(userRecharge.getReplyTime());
		
		//更改日志状态
		SiteUserAccountLog accountLog = new SiteUserAccountLog();
		accountLog.setOrderId(queryUserBuy.getOrderNo());
		accountLog.setUserId(userRecharge.getUserId());
		accountLog = siteUserAccountLogMapper.selectOne(accountLog);
		log.info("accountLog"+accountLog.getId()+"订单："+accountLog.getOrderId());
		SiteUserAccountLog updateAccountLog = new SiteUserAccountLog();
		if(accountLog != null){
			updateAccountLog.setId(accountLog.getId());
			updateAccountLog.setUpdateTime(new Date());
		}
		
		//充值失败
		if(Constants.RECHARGE_STATUS_3 == userRecharge.getStatus()){
			log.info("充值结果 充值失败！"+userRecharge.getUserId());
			userBuy.setStatus(Constants.COMMON_STATUS_2);
			siteUserBuyMapper.updateByPrimaryKeySelective(userBuy);
			
			if(updateAccountLog != null){
				updateAccountLog.setStatus(Constants.COMMON_STATUS_2);
				siteUserAccountLogMapper.updateByPrimaryKeySelective(updateAccountLog);
			}
			
			//购买失败加息券、红包退回
			if(StringUtils.isNotBlank(queryUserBuy.getCouponId())){
				log.info("充值结果 充值失败！退回已使用加息券：user_id:"+userRecharge.getUserId()+",订单号:"+queryUserBuy.getOrderNo()+",加息券id："+queryUserBuy.getCouponId());
				SiteUserCoupon updateCoupon = new SiteUserCoupon();
				updateCoupon.setId(Long.parseLong(queryUserBuy.getCouponId()));
				updateCoupon.setStatus(Constants.COMMON_STATUS_0);
				updateCoupon.setUseTime(new Date());
				siteUserCouponService.updateSiteUserCoupon(updateCoupon);
			}
			if(StringUtils.isNotBlank(queryUserBuy.getRedPacketId())){
				log.info("充值结果 充值失败！退回已使用红包：user_id:"+userRecharge.getUserId()+",订单号:"+queryUserBuy.getOrderNo()+",红包id："+queryUserBuy.getRedPacketId());
				SiteUserEnvelop updateEnvelop = new SiteUserEnvelop();
				updateEnvelop.setId(Long.parseLong(queryUserBuy.getRedPacketId()));
				updateEnvelop.setStatus(Constants.COMMON_STATUS_0);
				updateEnvelop.setUseTime(new Date());
				siteUserEnvelopService.updateSiteUserEnvelop(updateEnvelop);
			}
			return;
		}
		
		//充值成功
		userBuy.setStatus(Constants.COMMON_STATUS_1);
		log.info("充值结果 充值成功！"+userRecharge.getUserId());
		siteUserBuyMapper.updateByPrimaryKeySelective(userBuy);
		
		//更新日志状态
		if(updateAccountLog != null){
			log.info("充值结果 更新日志！"+updateAccountLog.getId()+updateAccountLog.getOrderId());
			updateAccountLog.setStatus(Constants.COMMON_STATUS_1);
			siteUserAccountLogMapper.updateByPrimaryKeySelective(updateAccountLog);
		}
		
		//首投送体验金,查询投资次数
		SiteUserBuyExample queryUserBuyExample = new SiteUserBuyExample();
		queryUserBuyExample.createCriteria().andUserIdEqualTo(queryUserBuy.getUserId());
		int orderNum = siteUserBuyMapper.selectCountByExample(queryUserBuyExample);
		
		//首投送体验金查询活动规则
		int ruleFlag = 0;
		ActivityRule activityRule = new ActivityRule();
		activityRule.setStatus(Constants.COMMON_STATUS_1);
		activityRule.setType(Constants.ACTIVITY_RULE_TYPE_INVEST);
		activityRule = activityRuleMapper.selectOne(activityRule);
		if(activityRule != null){
			log.info(activityRule.getStartDate()+","+HJBUT.currentDate());
			ActivityRuleExample activityRuleExample = new ActivityRuleExample();
			activityRuleExample.createCriteria().andStatusEqualTo(Constants.COMMON_STATUS_1).andTypeEqualTo(Constants.ACTIVITY_RULE_TYPE_INVEST)
			.andStartDateGreaterThanOrEqualTo(activityRule.getStartDate()).andEndDateGreaterThanOrEqualTo(HJBUT.currentDate());
			ruleFlag = activityRuleMapper.selectCountByExample(activityRuleExample);
			log.info("ruleFlag:"+ruleFlag);
		}
		//体验金金额
		BigDecimal experienceAmount = BigDecimal.ZERO;
		String experienceDesc = "";
		
		//活期产品
		if(Constants.PRODUCT_TYPE_1 == queryUserBuy.getProductType()){
			log.info("充值结果 充值成功！活期购买 新增待转入持有金额记录");
			//活期待转入持有金额 新增记录
			SiteUserCurrent siteUserCurrent = new SiteUserCurrent();
			siteUserCurrent.setAmount(queryUserBuy.getAmount());
			siteUserCurrent.setUserId(queryUserBuy.getUserId());
			siteUserCurrent.setInterestDate(queryUserBuy.getInterestDate());
			siteUserCurrent.setCashReturnDate(queryUserBuy.getCashReturnDate());
			siteUserCurrent.setStatus(Constants.COMMON_STATUS_0);
			siteUserCurrent.setCreateTime(new Date());
			siteUserCurrent.setOrderNo(queryUserBuy.getOrderNo());
			
			siteUserCurrentMapper.insertSelective(siteUserCurrent);
			
			//使用加息券，新增加息有限期
			if(StringUtils.isNotBlank(queryUserBuy.getCouponId())){
				SiteUserCoupon queryUserCoupon = new SiteUserCoupon();
				queryUserCoupon.setId(Long.parseLong(queryUserBuy.getCouponId()));
				SiteUserCoupon userCoupon = siteUserCouponMapper.selectOne(queryUserCoupon);
				if(userCoupon == null){
					log.info("充值结果 加息券不存在！"+queryUserBuy.getCouponId());
					return;
				}
				
				SiteUserAddRate siteUserAddRate = new SiteUserAddRate();
				siteUserAddRate.setUserId(queryUserBuy.getUserId());
				siteUserAddRate.setProductId(queryUserBuy.getProductId());
				siteUserAddRate.setCouponId(String.valueOf(userCoupon.getId()));
				siteUserAddRate.setStartDate(queryUserBuy.getInterestDate());
				siteUserAddRate.setEndDate(HJBUT.currentDate(queryUserBuy.getInterestDate(), userCoupon.getActiveDays()));
				siteUserAddRate.setAddRate(userCoupon.getAmount());
				siteUserAddRate.setStatus(Constants.COMMON_STATUS_0);
				siteUserAddRate.setCreateTime(HJBUT.currentTime());
				
				siteUserAddRateMapper.insertSelective(siteUserAddRate);
			}
			
			//更新用户定期
			SiteUserAccount userAccount = new SiteUserAccount();
			userAccount.setUserId(queryUserBuy.getUserId());
			userAccount = siteUserAccountMapper.selectOne(userAccount);
			//活期总计投资
			BigDecimal totalCurrentInvest = userAccount.getTotalCurrentInvest().add(queryUserBuy.getAmount());
			
			//更新账户信息
			SiteUserAccount updateUserAccount = new SiteUserAccount();
			updateUserAccount.setUserId(userAccount.getUserId());
			updateUserAccount.setTotalCurrentInvest(totalCurrentInvest);
			updateUserAccount.setTotalAsset(userAccount.getTotalAsset().add(queryUserBuy.getAmount()));
			siteUserAccountMapper.updateByPrimaryKeySelective(updateUserAccount);
			
			//首投送体验金
			experienceAmount = queryUserBuy.getAmount().multiply(new BigDecimal(5));
			experienceDesc = "首投活期";
//			SiteUserCurrentExample userCurrentExample = new SiteUserCurrentExample();
//			userCurrentExample.createCriteria().andUserIdEqualTo(queryUserBuy.getUserId());
//			int currentOrderNum = siteUserCurrentMapper.selectCountByExample(userCurrentExample);
//			if(orderNum == 1 && ruleFlag ==1){
//				siteUserAccountService.updateExperienceAccount(queryUserBuy.getUserId(), queryUserBuy.getAmount().multiply(new BigDecimal(5)), 1, null, null, "首投活期");
//			}
		}
		
		//定期产品
		if(Constants.PRODUCT_TYPE_2 == queryUserBuy.getProductType()){
			log.info("充值结果 充值成功！定期购买 新增待转入持有金额记录");
			int totalDays = 0;
			BigDecimal rate = BigDecimal.ZERO;
			BigDecimal addRate = BigDecimal.ZERO;
			BigDecimal couponAddRate = BigDecimal.ZERO;
			BigDecimal interest = BigDecimal.ZERO;
			BigDecimal addInterest = BigDecimal.ZERO;
			BigDecimal couponInterest = BigDecimal.ZERO;
			BigDecimal expectTip = BigDecimal.ZERO;
			
			//查询产品详情
			Product product = new Product();
			product.setProductId(queryUserBuy.getProductId());
			product = productMapper.selectOne(product);
			totalDays = product.getProductTime();
			if(product.getRate() != null){
				rate = product.getRate();
				interest = HJBUT.getInterest(queryUserBuy.getAmount(), rate, totalDays);
			}
			if(product.getAddRate() != null){
				addRate = product.getAddRate();
				addInterest = HJBUT.getInterest(queryUserBuy.getAmount(), addRate, totalDays);
			}
			if(queryUserBuy.getAddRate() != null){
				couponAddRate = queryUserBuy.getAddRate();
				couponInterest = HJBUT.getInterest(queryUserBuy.getAmount(), couponAddRate, totalDays);
			}
			if(queryUserBuy.getCash() != null){
				expectTip = queryUserBuy.getCash();
			}
			
			SiteUserFixed siteUserFixed = new SiteUserFixed();
			siteUserFixed.setUserId(queryUserBuy.getUserId());
			siteUserFixed.setProductId(queryUserBuy.getProductId());
			siteUserFixed.setAmount(queryUserBuy.getAmount());
			siteUserFixed.setAddRate(queryUserBuy.getAddRate());
			siteUserFixed.setReturnType(queryUserBuy.getReturnType());
			siteUserFixed.setInterestDate(queryUserBuy.getInterestDate());
			siteUserFixed.setCashReturnDate(queryUserBuy.getCashReturnDate());
			siteUserFixed.setStatus(Constants.COMMON_STATUS_0);
			siteUserFixed.setCreateTime(new Date());
			siteUserFixed.setOrderNo(queryUserBuy.getOrderNo());
			siteUserFixed.setExpectInterest(interest);
			siteUserFixed.setExpectAddInterest(addInterest);
			siteUserFixed.setExpectCoupon(couponInterest);
			siteUserFixed.setExpectTip(expectTip);
			siteUserFixed.setProductTime(product.getProductTime());
			siteUserFixed.setApplyDate(HJBUT.getCurrentDateNew(queryUserBuy.getApplyDate(), 0));
			
			siteUserFixedMapper.insertSelective(siteUserFixed);
			
			//更新用户定期
			SiteUserAccount userAccount = new SiteUserAccount();
			userAccount.setUserId(queryUserBuy.getUserId());
			userAccount = siteUserAccountMapper.selectOne(userAccount);
			
			//total_asset
			BigDecimal totalAsset = queryUserBuy.getAmount().add(interest).add(addInterest).add(couponInterest).add(expectTip);
			//定期待收总本息
			BigDecimal fixedExpectIncome = userAccount.getFixedExpectIncome().add(totalAsset);
			//定期待收本金
			BigDecimal fixedExpectPrinciple = userAccount.getFixedExpectPrinciple().add(queryUserBuy.getAmount());
			//定期待收利息
			BigDecimal fixedExpectInterest = userAccount.getFixedExpectInterest().add(interest);
			//定期待收平台加息
			BigDecimal fixedExpectAddInterest = userAccount.getFixedExpectAddInterest().add(addInterest);
			//定期待收加息劵收益
			BigDecimal fixedExpectCoupon = userAccount.getFixedExpectCoupon().add(couponInterest);
			//定期待收红包返现
			BigDecimal fixedExpectTip = userAccount.getFixedExpectTip().add(expectTip);
			//本次共计增加
			BigDecimal totalAmount = fixedExpectIncome.add(fixedExpectAddInterest).add(fixedExpectCoupon).add(fixedExpectTip);
			//定期总账户
//			BigDecimal fixedAccount = userAccount.getFixedAccount().add(totalAmount);
			//定期总投资
			BigDecimal totalFixedInvest = userAccount.getTotalFixedInvest().add(queryUserBuy.getAmount());
			
			//更新账户信息
			SiteUserAccount updateUserAccount = new SiteUserAccount();
			updateUserAccount.setUserId(userAccount.getUserId());
			updateUserAccount.setFixedExpectIncome(fixedExpectIncome);
			updateUserAccount.setFixedExpectPrinciple(fixedExpectPrinciple);
			updateUserAccount.setFixedExpectInterest(fixedExpectInterest);
			updateUserAccount.setFixedExpectAddInterest(fixedExpectAddInterest);
			updateUserAccount.setFixedExpectCoupon(fixedExpectCoupon);
			updateUserAccount.setFixedExpectTip(fixedExpectTip);
			updateUserAccount.setFixedAccount(totalAmount);
			updateUserAccount.setTotalAsset(userAccount.getTotalAsset().add(totalAsset));
			updateUserAccount.setTotalFixedInvest(totalFixedInvest);
			siteUserAccountMapper.updateByPrimaryKeySelective(updateUserAccount);
			
			//活期支付，系统账户记账
			if(queryUserBuy.getPayType().equals(Constants.PAY_TYPE_2)){
				log.info("定期购买，活期支付 系统账户记账开始..............");
				//更新系统活期账户
				String inMsg = "定期购买活期支付:定期order_no："+queryUserBuy.getOrderNo()+",投资金额："+queryUserBuy.getAmount();
				log.info(inMsg);
				siteSysAccountService.updateBanlanceByUserId(Constants.SYS_ACCOUNT_10002, queryUserBuy.getAmount(), BigDecimal.ZERO, Constants.ACCOUNT_LOG_TYPE_4, 
						siteUserFixed.getUserId(), Constants.SYS_ACCOUNT_10002,
						"", "", siteUserFixed.getOrderNo(), inMsg, "定期", "活期");
				
				//更新系统定期账户
				siteSysAccountService.updateBanlanceByUserId(Constants.SYS_ACCOUNT_10003, queryUserBuy.getAmount().negate(), BigDecimal.ZERO, Constants.ACCOUNT_LOG_TYPE_4, 
						siteUserFixed.getUserId(), Constants.SYS_ACCOUNT_10003,
						"", "", siteUserFixed.getOrderNo(), inMsg, "定期", "活期");
				log.info("定期购买，活期支付 系统账户记账结束..............");
			}
			
			//首投送体验金
			experienceAmount = queryUserBuy.getAmount().multiply(new BigDecimal(10));
			experienceDesc = "首投定期";
//			SiteUserFixedExample userFixedExample = new SiteUserFixedExample();
//			userFixedExample.createCriteria().andUserIdEqualTo(queryUserBuy.getUserId());
//			int fixedOrderNum = siteUserFixedMapper.selectCountByExample(userFixedExample);
//			if(orderNum == 1 && ruleFlag ==1){
//				siteUserAccountService.updateExperienceAccount(queryUserBuy.getUserId(), queryUserBuy.getAmount().multiply(new BigDecimal(10)), 1, null, null, "首投定期");
//			}
			
		}
		
		//首投发放体验金
		if(orderNum == 1 && ruleFlag ==1){
			siteUserAccountService.updateExperienceAccount(queryUserBuy.getUserId(), experienceAmount, 1, null, null, experienceDesc);
		}
		log.info("充值购买成功回调 结束................................."+HJBUT.currentTime());
		
	}

}
